package com.jingdianjichi.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.nacos.common.utils.StringUtils;
import com.google.gson.Gson;
import com.jingdianjichi.gateway.redis.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    RedisUtil redisUtil;

    private static final String AUTH_PERMISSION_PREFIX = "auth.permission";

    private static final String AUTH_ROLE_PREFIX = "auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        String authKey = redisUtil.buildKey(AUTH_PERMISSION_PREFIX, loginId.toString());
        String authValue = redisUtil.get(authKey);
//      isBlank判断为null或长度为0或全是空格
        if(StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<String> permissionList = new Gson().fromJson(authValue, List.class);
        return permissionList;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        String authKey = redisUtil.buildKey(AUTH_ROLE_PREFIX, loginId.toString());
        String authValue = redisUtil.get(authKey);
        if(StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<String> roleList = new Gson().fromJson(authValue, List.class);
        return roleList;
    }



}

